import React, { Component } from 'react'

// 导入子组件
import NavHeader from '../../components/NavHeader'
import HousePackage from '../../components/HousePackage'
import HouseItem from '../../components/HouseItem'

import styles from './index.module.scss'

import { Carousel, Flex, Toast, Modal } from 'antd-mobile'

import { BASE_URL } from '../../utils/url'

import { isAuth } from '../../utils'

// 猜你喜欢
const recommendHouses = [
  {
    id: 1,
    houseImg: '/newImg/7bk83o0cf.jpg',
    desc: '72.32㎡/南 北/低楼层',
    title: '安贞西里 3室1厅',
    price: 4500,
    tags: ['随时看房']
  },
  {
    id: 2,
    houseImg: '/newImg/7bk83o0cf.jpg',
    desc: '83㎡/南/高楼层',
    title: '天居园 2室1厅',
    price: 7200,
    tags: ['近地铁']
  },
  {
    id: 3,
    houseImg: '/newImg/7bk83o0cf.jpg',
    desc: '52㎡/西南/低楼层',
    title: '角门甲4号院 1室1厅',
    price: 4300,
    tags: ['集中供暖']
  }
]

// 百度地图
const BMap = window.BMap

const labelStyle = {
  position: 'absolute',
  zIndex: -7982820,
  backgroundColor: 'rgb(238, 93, 91)',
  color: 'rgb(255, 255, 255)',
  height: 25,
  padding: '5px 10px',
  lineHeight: '14px',
  borderRadius: 3,
  boxShadow: 'rgb(204, 204, 204) 2px 2px 2px',
  whiteSpace: 'nowrap',
  fontSize: 12,
  userSelect: 'none'
}

class HouseDetail extends Component {
  state = {
    isLoading: false,

    // 轮播图图片高度
    imgHeight: 252,

    houseInfo: {
      // 房屋图片
      houseImg: [],
      // 标题
      title: '',
      // 标签
      tags: [],
      // 租金
      price: 0,
      // 房型
      roomType: '两室一厅',
      // 房屋面积
      size: 89,
      // 装修类型
      renovation: '精装',
      // 朝向
      oriented: [],
      // 楼层
      floor: '',
      // 小区名称
      community: '加载中...',
      // 地理位置
      coord: {
        latitude: '39.928033',
        longitude: '116.529466'
      },
      // 房屋配套
      supporting: [],
      // 房屋标识
      houseCode: '',
      // 房屋描述
      description: ''
    },

    // 是否收藏
    isFavorite: false
  }

  // 渲染轮播图结构
  renderSwipers() {
    const {
      imgHeight,
      houseInfo: { houseImg }
    } = this.state

    return houseImg.map(item => (
      <a
        key={item}
        href="http://itcast.cn"
        style={{
          display: 'inline-block',
          width: '100%',
          height: imgHeight
        }}
      >
        <img
          src={BASE_URL + item}
          alt=""
          style={{ width: '100%', height: '100%', verticalAlign: 'top' }}
          onLoad={() => {
            // fire window resize event to change height
            window.dispatchEvent(new Event('resize'))
            this.setState({ imgHeight: '252' })
          }}
        />
      </a>
    ))
  }

  // 渲染地图
  renderMap(community, coord) {
    const { latitude, longitude } = coord

    const map = new BMap.Map('map')
    const point = new BMap.Point(longitude, latitude)
    map.centerAndZoom(point, 17)

    const label = new BMap.Label('', {
      position: point,
      offset: new BMap.Size(0, -36)
    })

    label.setStyle(labelStyle)
    label.setContent(`
          <span>${community}</span>
          <div class="${styles.mapArrow}"></div>
        `)
    map.addOverlay(label)
  }

  async componentDidMount() {
    const {
      params: { id }
    } = this.props.match

    this.id = id

    // 获取房屋详情数据
    this.getHouseDetailData()

    // 获取房屋收藏状态
    this.checkFavorite()
  }

  // 获取房屋详情数据
  async getHouseDetailData() {
    // 发送网路请求，获取详情数据
    const result = await this.$axios.get(`houses/${this.id}`)

    if (result.data.status === 200) {
      const {
        body: { community, coord }
      } = result.data

      this.setState({
        houseInfo: result.data.body
      })

      // 渲染小区地图
      this.renderMap(community, coord)
    }
  }

  // 获取收藏状态
  async checkFavorite() {
    if (!isAuth()) return

    const result = await this.$axios.get(`user/favorites/${this.id}`)

    const { status, body } = result.data
    if (status === 200) {
      this.setState({
        isFavorite: body.isFavorite
      })
    }
  }

  // 处理收藏与取消收藏
  handleFavorite = async () => {
    // 判断是否登录，如果没有登录则提示
    if (!isAuth()) {
      this.goToLogin('登录后才能收藏房源，是否去登录？')
      return
    }

    if (this.state.isFavorite) {
      // 已收藏则取消收藏
      const result = await this.$axios.delete(`user/favorites/${this.id}`)

      const { status, description } = result.data

      if (status === 200) {
        Toast.info(description, 2)

        this.setState({
          isFavorite: false
        })
      } else {
        this.goToLogin('登录超时，是否重新登录？')
      }
    } else {
      // 没收藏则收藏
      const result = await this.$axios.post(`user/favorites/${this.id}`)

      const { status, description } = result.data
      if (status === 200) {
        Toast.info(description, 1)

        this.setState({
          isFavorite: true
        })
      } else {
        this.goToLogin('登录超时，是否重新登录？')
      }
    }
  }

  // 跳转到登录页面
  goToLogin = title => {
    Modal.alert('提示', title, [
      { text: '取消' },
      {
        text: '去登录',
        onPress: () => {
          this.props.history.push('/login')
        }
      }
    ])
  }

  render() {
    const {
      isLoading,
      houseInfo: {
        community,
        description,
        floor,
        oriented,
        price,
        roomType,
        size,
        tags,
        title,
        supporting
      },
      isFavorite
    } = this.state

    return (
      <div className={styles.root}>
        <NavHeader
          className={styles.detailHeader}
          rightContent={[<i key="share" className="iconfont icon-share" />]}
        >
          {community}
        </NavHeader>

        {/* 轮播图 */}
        <div className={styles.slides}>
          {!isLoading ? (
            <Carousel autoplay infinite autoplayInterval={5000}>
              {this.renderSwipers()}
            </Carousel>
          ) : (
            ''
          )}
        </div>

        {/* 房屋基础信息 */}
        <div className={styles.info}>
          <h3 className={styles.infoTitle}>{title}</h3>
          <Flex className={styles.tags}>
            <Flex.Item>
              {tags &&
                tags.map((item, index) => {
                  const tagName = `tag${(index % 3) + 1}`
                  return (
                    <span
                      key={index}
                      className={[styles.tag, styles[tagName]].join(' ')}
                    >
                      {item}
                    </span>
                  )
                })}
            </Flex.Item>
          </Flex>

          <Flex className={styles.infoPrice}>
            <Flex.Item className={styles.infoPriceItem}>
              <div>
                {price}
                <span className={styles.month}>/月</span>
              </div>
              <div>租金</div>
            </Flex.Item>
            <Flex.Item className={styles.infoPriceItem}>
              <div>{roomType}</div>
              <div>房型</div>
            </Flex.Item>
            <Flex.Item className={styles.infoPriceItem}>
              <div>{size}</div>
              <div>面积</div>
            </Flex.Item>
          </Flex>

          <Flex className={styles.infoBasic} align="center">
            <Flex.Item>
              <div>
                <span className={styles.title}>装修：</span>
                精装修
              </div>
              <div>
                <span className={styles.title}>楼层：</span>
                {floor}
              </div>
            </Flex.Item>
            <Flex.Item>
              <div>
                <span className={styles.title}>朝向：</span>
                {oriented.join(' ')}
              </div>
              <div>
                <span className={styles.title}>类型：</span>普通住宅
              </div>
            </Flex.Item>
          </Flex>
        </div>

        {/* 地图位置 */}
        <div className={styles.map}>
          <div className={styles.mapTitle}>
            小区：
            <span>{community}</span>
          </div>
          <div className={styles.mapContainer} id="map">
            地图
          </div>
        </div>

        {/* 房屋配套 */}
        <div className={styles.about}>
          <div className={styles.houseTitle}>房屋配套</div>
          {/* <HousePackage
            list={[
              '电视',
              '冰箱',
              '洗衣机',
              '空调',
              '热水器',
              '沙发',
              '衣柜',
              '天然气'
            ]}
          /> */}
          {/* <div className="title-empty">暂无数据</div> */}
          {supporting && supporting.length > 0 ? (
            <HousePackage list={supporting} />
          ) : (
            <div className={styles.titleEmpty}>暂无数据</div>
          )}
        </div>

        {/* 房屋概况 */}
        <div className={styles.set}>
          <div className={styles.houseTitle}>房源概况</div>
          <div>
            <div className={styles.contact}>
              <div className={styles.user}>
                <img src={BASE_URL + '/img/avatar.png'} alt="头像" />
                <div className={styles.useInfo}>
                  <div>王女士</div>
                  <div className={styles.userAuth}>
                    <i className="iconfont icon-auth" />
                    已认证房主
                  </div>
                </div>
              </div>
              <span className={styles.userMsg}>发消息</span>
            </div>

            <div className={styles.descText}>
              {description || '暂无房屋描述'}
              {/* 1.周边配套齐全，地铁四号线陶然亭站，交通便利，公交云集，距离北京南站、西站都很近距离。
              2.小区规模大，配套全年，幼儿园，体育场，游泳馆，养老院，小学。
              3.人车分流，环境优美。
              4.精装两居室，居家生活方便，还有一个小书房，看房随时联系。 */}
            </div>
          </div>
        </div>

        {/* 推荐 */}
        <div className={styles.recommend}>
          <div className={styles.houseTitle}>猜你喜欢</div>
          <div className={styles.items}>
            {recommendHouses.map(item => (
              <HouseItem {...item} key={item.id} onClick={a => a} />
            ))}
          </div>
        </div>

        {/* 底部收藏按钮 */}
        <Flex className={styles.fixedBottom}>
          <Flex.Item onClick={this.handleFavorite}>
            {isFavorite ? (
              <>
                <img
                  src={BASE_URL + '/img/star.png'}
                  className={styles.favoriteImg}
                  alt="收藏"
                />
                <span className={styles.favorite}>已收藏</span>
              </>
            ) : (
              <>
                <img
                  src={BASE_URL + '/img/unstar.png'}
                  className={styles.favoriteImg}
                  alt="收藏"
                />
                <span className={styles.favorite}>收藏</span>
              </>
            )}
          </Flex.Item>
          <Flex.Item>在线咨询</Flex.Item>
          <Flex.Item>
            <a href="tel:400-618-4000" className={styles.telephone}>
              电话预约
            </a>
          </Flex.Item>
        </Flex>
      </div>
    )
  }
}

export default HouseDetail
